﻿using System.Windows;
using System.Windows.Controls;

namespace StockholmsStad.Windows.UI.Infrastructure.Controls
{
    public class ExtendedRadioButton : RadioButton
    {
        private static bool m_bIsChanging;

        public ExtendedRadioButton()
        {
            Checked += RadioButtonExtended_Checked;
            Unchecked += RadioButtonExtended_Unchecked;
        }

        private void RadioButtonExtended_Unchecked(object sender, RoutedEventArgs e)
        {
            if (!m_bIsChanging)
                IsCheckedReal = false;
        }

        private void RadioButtonExtended_Checked(object sender, RoutedEventArgs e)
        {
            if (!m_bIsChanging)
                IsCheckedReal = true;
        }

        public bool IsCheckedReal
        {
            get { return (bool) GetValue(IsCheckedRealProperty); }
            set { SetValue(IsCheckedRealProperty, value); }
        }

        // Using a DependencyProperty as the backing store for IsCheckedReal. This enables animation, styling, binding, etc...
        public static readonly DependencyProperty IsCheckedRealProperty =
            DependencyProperty.Register("IsCheckedReal", typeof (bool?), typeof (ExtendedRadioButton),
                                        new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.Journal |
                                                                             FrameworkPropertyMetadataOptions.
                                                                                 BindsTwoWayByDefault,
                                                                      IsCheckedRealChanged));

        public static void IsCheckedRealChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            m_bIsChanging = true;
            ((ExtendedRadioButton) d).IsChecked = (bool) e.NewValue;
            m_bIsChanging = false;
        }
    }
}